from django.shortcuts import render
from django.http import HttpResponse
import json
import qrcode
import copy
import random

pwd = '3582'
names = ['李想', '李雪龙', '邓翔', '郑家明', '林声琦', '黄岳嘉', '卢子辰']
now_status = 0
lucky_names = ['李想']
chosen_set = set()
# Create your views here.
def select(request):
    context = {}
    return render(request, 'select.html', context)

def index(request):
    context = {}
    return render(request, 'index.html', context)

def info(request):
    context = {}
    return render(request, 'info.html', context)

def submit(request):
    user_name = ''
    password = ''
    try:
        user_name = request.POST['user_name']
        password = request.POST['password']
    except Exception:
        pass
    if len(user_name) > 0:
        names.append(user_name)
    context = {}
    if password == pwd:
        return render(request, 'select_expert.html', context)
    else:
        return render(request, 'select.html', context)

def get_names(request):
    new_names = list()
    while len(new_names) < 40:
        new_names += copy.deepcopy(names)
    return HttpResponse(json.dumps(new_names, ensure_ascii=False))

def set_status(request):
    status = 0
    try:
        status = request.POST['running_status']
    except Exception:
        pass
    if status == '2':
        lucky_name_list = list(set(names))
        idx = random.randint(0, len(lucky_name_list) - 1)
        while lucky_name_list[idx] in chosen_set and len(chosen_set) + 5 < len(lucky_name_list):
            idx = random.randint(0, len(lucky_name_list) - 1)
        idx2 = random.randint(0, len(lucky_name_list) - 1)
        while len(lucky_name_list) > 1 and idx == idx2 or \
            len(chosen_set) + 5 < len(lucky_name_list) and lucky_name_list[idx2] in chosen_set:
            idx2 = random.randint(0, len(lucky_name_list) - 1)
        global lucky_names
        lucky_names = [lucky_name_list[idx], lucky_name_list[idx2]]
        chosen_set.add(lucky_name_list[idx])
        chosen_set.add(lucky_name_list[idx2])
    global now_status
    now_status = status
    return HttpResponse('success')

def get_status(request):
    status = [now_status]
    return HttpResponse(json.dumps(status, ensure_ascii=False))

def lucky(request):
    return HttpResponse(json.dumps(lucky_names, ensure_ascii=False))

def test(request):
    return render(request, 'select_expert.html', {})
